package com.myapidemos.apps.app;

import com.example.myapidemos.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.Toast;

public class MessageService extends Service {
	static final int MSG_REGISTER_CLIENT = 1;
	static final int MSG_UNREGISTER_CLIENT = 2;
	static final int MSG_SET_VALUE = 3;

	class InCommingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case MSG_REGISTER_CLIENT:
					msg.replyTo.send(Message.obtain(null, MSG_REGISTER_CLIENT));
					break;
				case MSG_UNREGISTER_CLIENT:
					msg.replyTo.send(Message.obtain(null, MSG_UNREGISTER_CLIENT));
					break;
				case MSG_SET_VALUE:
					msg.replyTo.send(Message.obtain(null, MSG_SET_VALUE));
					break;
				default:
					super.handleMessage(msg);
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	Messenger mMessenger = new Messenger(new InCommingHandler());

	NotificationManager nNM = null;

	@Override
	public IBinder onBind(Intent intent) {
		return mMessenger.getBinder();
	}

	@Override
	public void onCreate() {
		nNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		showNotification();
	}

	@Override
	public void onDestroy() {
		nNM.cancel(R.string.remote_service_started);

		Toast.makeText(MessageService.this, R.string.remote_service_stopped, Toast.LENGTH_SHORT)
				.show();
	}

	private void showNotification() {
		CharSequence s = getText(R.string.remote_service_started);
		Notification notification = new Notification(R.drawable.ic_launcher, s,
				System.currentTimeMillis());
		PendingIntent intent = PendingIntent.getActivity(MessageService.this, 0, new Intent(this,
				MessageServiceActivity.class), 0);
		notification.setLatestEventInfo(this, "running", "starting?", intent);
		nNM.notify(R.string.remote_service_started, notification);
	}

}
